/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package sessionbean;

import entitybean.Albums;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author Thien Nguyen
 */
@Stateless
@org.jboss.ejb3.annotation.RemoteBinding(jndiBinding="AlbumsJNDI")
@org.jboss.ejb3.annotation.LocalBinding(jndiBinding = "AlbumsLocalJNDI")
public class AlbumSessionBean implements AlbumSessionBeanRemote, AlbumSessionBeanLocal {
    @PersistenceContext(unitName = "J2EE_ShareMusic-ejbPU")
    private EntityManager em;

    public void persist(Object object) {
        em.persist(object);
    }

    public List loadAlbum() {
        String jpql = "SELECT a FROM Albums a";
        javax.persistence.Query query = em.createQuery(jpql);
        List list = query.getResultList();
        return list;
    }

    public List getAlbum(int id) {
        String jpql = "SELECT a FROM Albums a WHERE a.albumID =:id";
        javax.persistence.Query query = em.createQuery(jpql);
        query.setParameter("id", id);
        List list = query.getResultList();
        return list;
    }

    public boolean addAlbum(String name, String url) {
        String jpql = "SELECT a FROM Albums a WHERE a.albumName =:name AND a.imageUrl =:url";
        javax.persistence.Query query = em.createQuery(jpql);
        query.setParameter("name", name);
        query.setParameter("url", url);
        List list = query.getResultList();
        if (list.size() == 0) {
            Albums newA = new Albums(name, url);
            persist(newA);
            return true;
        } else {
            return false;
        }
    }

    public boolean deleteAlbum(int id) {
        String jpql = "UPDATE Songs a SET a.albums.albumID =:param WHERE a.albums.albumID =:id";
        javax.persistence.Query query = em.createQuery(jpql);
        query.setParameter("param", null);
        query.setParameter("id", id);
        int result = query.executeUpdate();
        Albums album = em.find(Albums.class, id);
        if(album != null) {
            em.remove(album);
            return true;
        }
        return false;
    }

    public boolean saveAlbum(int id, String url) {
        String jpql = "UPDATE Albums a SET a.imageUrl =:url WHERE a.albumID =:id";
        javax.persistence.Query query = em.createQuery(jpql);
        query.setParameter("url", url);
        query.setParameter("id", id);
        int result = query.executeUpdate();
        if(result > 0) return true;
        else return false;
    }
    
    
}
